<!-- pages/index/index.vue -->
<template>
  <view>
    <canvas canvas-id="canvas1" style="width: 300px; height: 300px;"></canvas>
    <canvas canvas-id="canvas2" style="width: 300px; height: 300px;"></canvas>
    <canvas canvas-id="mergedCanvas" style="width: 300px; height: 300px;"></canvas>
    <button @click="mergeCanvases">Merge Canvases</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 300,
      canvasHeight: 300
    }
  },
  onReady() {
    this.ctx1 =  uni.createCanvasContext("canvas1");
    this.ctx2 = uni.createCanvasContext("canvas2");
    this.ctxMerged = uni.createCanvasContext("mergedCanvas");

    this.drawCanvas1();
    this.drawCanvas2();
  },
  methods: {
    drawCanvas1() {
      this.ctx1.beginPath();
      this.ctx1.arc(100, 100, 50, 0, 2 * Math.PI);
      this.ctx1.setFillStyle('red');
      this.ctx1.fill();
    },
    drawCanvas2() {
      this.ctx2.beginPath();
      this.ctx2.rect(50, 50, 200, 100);
      this.ctx2.setFillStyle('blue');
      this.ctx2.fill();
    },
    mergeCanvases() {
      const { canvasWidth, canvasHeight } = this;

      // 获取 canvas1 的图像数据
      this.ctx1.draw(false, () => {
        this.ctx2.draw(false, () => {
          const imageData1 = this.ctx1.getImageData(0, 0, canvasWidth, canvasHeight);
          const imageData2 = this.ctx2.getImageData(0, 0, canvasWidth, canvasHeight);

          // 合并图像数据
          const mergedImageData = new Uint8ClampedArray(imageData1.data.length);
          for (let i = 0; i < imageData1.data.length; i += 4) {
            mergedImageData[i] = imageData1.data[i]; // R
            mergedImageData[i + 1] = imageData1.data[i + 1]; // G
            mergedImageData[i + 2] = imageData1.data[i + 2]; // B
            mergedImageData[i + 3] = Math.max(imageData1.data[i + 3], imageData2.data[i + 3]); // A
          }

          // 将合并后的图像数据绘制到 mergedCanvas 上
          this.ctxMerged.putImageData(new ImageData(mergedImageData, canvasWidth, canvasHeight), 0, 0);
          this.ctxMerged.draw();
        });
      });
    }
  }
}
</script>